<template>
  <div v-if="code">
    <div class="code-title">{{code.title}}</div>
    <pre-code :code="code"></pre-code>
    <!-- 上一个，下一个 -->
    <adjoin :list="list" />
  </div>
</template>
<script>
// https://blog.csdn.net/weixin_43376417/article/details/124174325
import codeApi from '@/api/code'
export default {
  components: {
    preCode: () => import("@/components/PreCode.vue"),
    adjoin: () => import("@/components/AdJoin.vue"),
  },
  data() {
    return {
      code: {},
      list: [],

    };
  },

  mounted() {
    this.id = this.$route.query.id;
    if (this.id) {
      this.getData(this.id);
      //得到activeKey
    } else {
      this.getItemFirst();
      this.$store.dispatch("app/setActiveKey", "0");
    };
    // this.getData();
  },
  watch: {
    $route: {
      handler: function(nv, ov) {
        this.id = this.$route.query.id;
        if (nv) {
          this.getData(this.id);
          this.getAdjoin();
        }
      },
      deep: true,
    },
  },
  methods: {
    getAdjoin() {
      codeApi.adjoin({ id: this.id }).then(res => {
        this.list = res.result;
      })
    },
    getData(id) {
      let code = {};
      if (id) {
        code.id = id;
      }
      codeApi.get(code).then(res => {
        const result = this.handleList(res.result)
        this.code = result[0].children[0]; //按照id取得的第一项
        console.log(this.code);
        this.getAdjoin()
      })
    },
    getItemFirst() {
      codeApi.get().then(res => {
        const result = this.handleList(res.result)
        this.code = result[0].children[0]; //按照id取得的第一项
        this.id = this.code._id;
        this.$router.push('/code?id=' + this.id)
        this.getAdjoin()
      })
    },
    handleList(arr) {
      let alpha_dict = new Object();
      let factories = new Array();
      for (var i = 0; i < arr.length; i++) {
        let factory = arr[i];
        let key = factory.key;
        if (alpha_dict[key] == undefined) {
          factories.push({
            "key": key,
            "children": [factory]
          });
          alpha_dict[key] = factories.length - 1;
        } else {
          factories[alpha_dict[key]].children.push(factory);
        }
      }
      return factories;
    },
  },
};

</script>
<style>
</style>
